package util;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import top.ConfigCenter;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

public class RequestFileDispatcher {

    HashMap<String, String>   params;
    HashMap<String, FileItem> files;

    private static final int DEFAULT_MEMORY_THRESHOLD = Integer.parseInt(ConfigCenter.getFileUploadConfig("DEFAULT_MEMORY_THRESHOLD"));
    private static final int DEFAULT_MAX_FILE_SIZE    = Integer.parseInt(ConfigCenter.getFileUploadConfig("DEFAULT_MAX_FILE_SIZE"));
    private static final int DEFAULT_MAX_REQUEST_SIZE = Integer.parseInt(ConfigCenter.getFileUploadConfig("DEFAULT_MAX_REQUEST_SIZE"));

    public RequestFileDispatcher(HttpServletRequest req, boolean limitedBufferSize, boolean limitedFileSize, int bufferSize, int maxfileSize, int maxReceiveSize) throws FileUploadException, UnsupportedEncodingException {
        if(!ServletFileUpload.isMultipartContent(req)) throw new FileUploadException("提交的请求不是Multipart内容。");

        params = new HashMap<>();
        files  = new HashMap<>();

        DiskFileItemFactory fileItemBuffer = new DiskFileItemFactory();

        if(limitedBufferSize) {
            //最大内存缓冲大小（服务器内存控制）
            fileItemBuffer.setSizeThreshold(bufferSize);
            fileItemBuffer.setRepository(new File(System.getProperty("java.io.tmpdir")));
        }

        ServletFileUpload upload = new ServletFileUpload(fileItemBuffer);

        if(limitedFileSize) {
            upload.setFileSizeMax(maxfileSize);//最大单文件上传大小
            upload.setSizeMax(maxReceiveSize); //最大请求上传大小
        }

        upload.setHeaderEncoding("UTF-8");

        List<FileItem> received = upload.parseRequest(req);

        if(received != null  &&  received.size() > 0) for(FileItem item : received) {
            if(item.isFormField()) {
                params.put(item.getFieldName(), item.getString("UTF-8"));
            } else {
                files.put(item.getFieldName(), item);
            }
        }
    }

    public RequestFileDispatcher(HttpServletRequest req, int bufferSize, int maxfileSize, int maxReceiveSize)
            throws FileUploadException, UnsupportedEncodingException {
        this(req, true, true, bufferSize, maxfileSize, maxReceiveSize);
    }

    public RequestFileDispatcher(HttpServletRequest req)
            throws FileUploadException, UnsupportedEncodingException {
        this(req, false, false, 0, 0, 0);
    }

    public RequestFileDispatcher(HttpServletRequest req, int bufferSize)
            throws FileUploadException, UnsupportedEncodingException {
        this(req, true, false, bufferSize, 0, 0);
    }

    public String getParam(String name) {
        return params.get(name);
    }

    public FileItem getFileItem(String name) {
        return files.get(name);
    }
}
